//
//  AYSCommonPlayViewController.m
//  AiYingShiProject
//
//  Created by lanou on 15/10/28.
//  Copyright (c) 2015年 李晓理. All rights reserved.
//

#import "AYSCommonPlayViewController.h"
#import "AYSPlayDataModel.h"
#import "AYSPlayVideoModel.h"
#import "AYSRequestManager.h"
#import "AYSPlayUrlModel.h"
#import "AYSPlayVideoChooseCell.h"
#import "AYSPlayDetailView.h"
#import <UIImageView+WebCache.h>
#import "AYSChannelChooseCell.h"
#import "AYSVideoPlayerViewController.h"
#import "AYSDatabaseHandle.h"
#import "SVProgressHUD.h"
#import "FMDatabase.h"
@interface AYSCommonPlayViewController ()<UIScrollViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UIAlertViewDelegate>

@property (nonatomic,strong) AYSPlayDataModel *dataModel;  // 详情model
@property (nonatomic,strong) AYSPlayVideoModel *videoModel;   // 播放网址model
@property (nonatomic,strong) NSMutableArray *videoArray;   // 播放地址array
@property (nonatomic,strong) UIScrollView *mainScrollView;  // 最大的scrollView
@property (nonatomic,strong) UIImageView *postImageView;    // 图片
@property (nonatomic,strong) UILabel *updateLabel;         // 更新至
@property (nonatomic,strong) UIButton *playButton;         // 播放按钮
@property (nonatomic,strong) UIButton *downloadButton;     // 下载按钮
@property (nonatomic,strong) UISegmentedControl *segmentedControl;   // 分类
@property (nonatomic,strong) UICollectionView *collectionView;      // 选择集数的View
@property (nonatomic,strong) UIScrollView *chooseScrollView;        // 选择1-几百集的scrollView
@property (nonatomic,strong) UIButton *chooseButton;               // 选择1-100集的按钮
@property (nonatomic,strong) AYSPlayDetailView *detailView;       // 详细信息界面
@property (nonatomic,strong) UICollectionView *channelChooseCV;    // 选择播放源的View

@property (nonatomic, strong) AYSVideoPlayerViewController *player;
@property (nonatomic, assign) BOOL isHave;

@property (nonatomic, strong) FMDatabase *dataBase;

@end

@implementation AYSCommonPlayViewController

// 懒加载
- (NSMutableArray *)videoArray
{
    if (!_videoArray)
    {
        self.videoArray = [NSMutableArray array];
    }
    return _videoArray;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithWhite:0.043 alpha:1.000];
    self.navigationController.navigationBar.hidden = YES;
    [SVProgressHUD showInfoWithStatus:@"正在加载"];
    [self requestData];
    [SVProgressHUD dismiss];
    [self configureView];
    
    // 注册cell
    [_collectionView registerClass:[AYSPlayVideoChooseCell class] forCellWithReuseIdentifier:@"choose"];
    [_channelChooseCV registerClass:[AYSChannelChooseCell class] forCellWithReuseIdentifier:@"channel"];
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"AYSWatchRecord.db"];
    NSLog(@"%@", filePath);
    _dataBase = [FMDatabase databaseWithPath:filePath];
    if ([_dataBase open])
    {
        [_dataBase executeUpdate:@"CREATE TABLE WATCHRECORD (title text)"];
    }
    else
    {
        NSLog(@"数据库打开失败");
    }
}

// 点击播放按钮
- (void)didClickPlayButton:(UIButton *)sender
{
    _player = [[AYSVideoPlayerViewController alloc] init];
    _player.url = ((AYSPlayVideoModel *)self.videoArray[0]).videourl;
    [self presentViewController:_player animated:YES completion:nil];
    
    [_dataBase executeUpdate:@"INSERT INTO WATCHRECORD (title) VALUES (?)", _dataModel.programname];
}

// 配置view
- (void)configureView
{
    // 最大的scrollView
    _mainScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 65, SCREEN_WIDTH, SCREEN_HEIGHT - 65)];
    _mainScrollView.backgroundColor = [UIColor colorWithWhite:0.092 alpha:1.000];
    _mainScrollView.delegate = self;
    _mainScrollView.contentSize = CGSizeMake(SCREEN_WIDTH, 1050);
    _mainScrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_mainScrollView];
    
    // 海报图片
    _postImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, SCREEN_WIDTH /3 , SCREEN_HEIGHT / 4)];
    _postImageView.backgroundColor = [UIColor whiteColor];
    [_mainScrollView addSubview:_postImageView];
    
    // 更新至
    _updateLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 3 + 20, 20, SCREEN_WIDTH - (SCREEN_WIDTH / 3 + 20), 30)];
    _updateLabel.textColor = [UIColor redColor];
    [_mainScrollView addSubview:_updateLabel];
    
    // 选择播放网站
    UICollectionViewFlowLayout *channelLayout = [[UICollectionViewFlowLayout alloc] init];
    channelLayout.itemSize = CGSizeMake(25, 25);
    channelLayout.minimumInteritemSpacing = 10;
    channelLayout.minimumLineSpacing = 10;
    _channelChooseCV  = [[UICollectionView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 3 + 20, 70, SCREEN_WIDTH - (SCREEN_WIDTH / 3 + 20), 30) collectionViewLayout:channelLayout];
    _channelChooseCV.delegate = self;
    _channelChooseCV.dataSource = self;
    _channelChooseCV.tag = 101;
    _channelChooseCV.backgroundColor = [UIColor clearColor];
    [_mainScrollView addSubview:_channelChooseCV];
    
    // 播放按钮
    _playButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
    _playButton.frame = CGRectMake(SCREEN_WIDTH / 3 + 25, 110, SCREEN_WIDTH / 3-25 , 30);
    // 实现边框颜色
    _playButton.layer.masksToBounds = YES;
    _playButton.layer.cornerRadius = 5;
    _playButton.layer.borderWidth = 1;
    [_playButton addTarget:self action:@selector(didClickPlayButton:) forControlEvents:(UIControlEventTouchUpInside)];
    CGColorSpaceRef coloreSpe = CGColorSpaceCreateDeviceRGB();
    CGColorRef coolor = CGColorCreate(coloreSpe, (CGFloat[]){1,1,1,1});
    [_playButton.layer setBorderColor:coolor];
    
    UIImageView *playImage = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH / 3 - 25) / 2-35, 5, 20, 20)];
    playImage.image = [UIImage imageNamed:@"play"];
    [_playButton addSubview:playImage];
    
    UILabel *playLabel = [[UILabel alloc] initWithFrame:CGRectMake((SCREEN_WIDTH / 3 - 25) / 2, 5, 40 ,20)];
    playLabel.textColor = [UIColor whiteColor];
    playLabel.text = @"播放";
    [_playButton addSubview:playLabel];
    [_mainScrollView addSubview:_playButton];
    
    // 收藏按钮
    _downloadButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _downloadButton.frame = CGRectMake((SCREEN_WIDTH / 3 + 25) + (SCREEN_WIDTH / 3 - 25) + 15, 110, SCREEN_WIDTH / 3 - 25, 30);
    // 实现边框颜色
    _downloadButton.layer.masksToBounds = YES;
    _downloadButton.layer.cornerRadius = 5;
    _downloadButton.layer.borderWidth = 1;
    CGColorSpaceRef coloreSpe1 = CGColorSpaceCreateDeviceRGB();
    CGColorRef coolor1 = CGColorCreate(coloreSpe1, (CGFloat[]){1,1,1,1});
    [_downloadButton.layer setBorderColor:coolor1];
    [_downloadButton addTarget:self action:@selector(clickButton:) forControlEvents:(UIControlEventTouchUpInside)];
    
    UIImageView *collectView = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH / 3 - 25) / 2 - 35, 5, 20, 20)];
    collectView.image = [UIImage imageNamed:@"colllect"];
    [_downloadButton addSubview:collectView];
    
    
    UILabel *playLabel1 = [[UILabel alloc] initWithFrame:CGRectMake((SCREEN_WIDTH / 3 - 25) / 2, 5, 40 ,20)];
    playLabel1.textColor = [UIColor whiteColor];
    playLabel1.text = @"收藏";
    [_downloadButton addSubview:playLabel1];
    [_mainScrollView addSubview:_playButton];
    [_mainScrollView addSubview:_downloadButton];
    
    // 选择集数/详情
    _segmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"选集",@"详情"]];
    _segmentedControl.tintColor = [UIColor colorWithWhite:0.831 alpha:1.000];
    _segmentedControl.frame = CGRectMake(45, SCREEN_HEIGHT / 4 + 30, SCREEN_WIDTH - 100, 25);
    _segmentedControl.selectedSegmentIndex = 0;
    [_segmentedControl addTarget:self action:@selector(changeView:) forControlEvents:(UIControlEventValueChanged)];
    [_mainScrollView addSubview:_segmentedControl];
    
    // 选择集数按钮
    _chooseScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT / 4 + 60, SCREEN_WIDTH, 30)];
    _chooseScrollView.delegate = self;
    _chooseScrollView.backgroundColor = [UIColor colorWithWhite:0.071 alpha:1.000];
    _chooseScrollView.contentSize = CGSizeMake(SCREEN_WIDTH + 200, 20);
    _chooseScrollView.showsHorizontalScrollIndicator = NO;
    [_mainScrollView addSubview:_chooseScrollView];
    
    
    
    // 集数选择
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake((SCREEN_WIDTH - 50) / 4 - 10, 20);
    layout.minimumInteritemSpacing = 10;
    layout.minimumLineSpacing = 10;
    layout.sectionInset = UIEdgeInsetsMake(15, 15, 15, 15);
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT / 4 + 90, SCREEN_WIDTH, SCREEN_HEIGHT + 500)collectionViewLayout:layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.tag = 102;
    [_mainScrollView addSubview:_collectionView];
    
    // 详情界面
    _detailView = [[AYSPlayDetailView alloc] init];
    _detailView.frame = CGRectMake(0, SCREEN_HEIGHT / 4 + 60, SCREEN_WIDTH, SCREEN_HEIGHT + 500);
    _detailView.backgroundColor = [UIColor colorWithWhite:0.088 alpha:1.000];
    //[_mainScrollView addSubview:_detailView];
    
}
// 数据请求
- (void)requestData
{
    NSString *url = [NSString stringWithFormat:@"http://doukantv.com/api/program/?id=%@&sys_ver=9.1&cli=iphone&ver=2.3.4",self.programeID];
    [AYSRequestManager requestWithType:GET url:url parDic:nil finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        
        // dataModel请求数据
        NSDictionary *dict = dic[@"data"];
        _dataModel = [[AYSPlayDataModel alloc] init];
        [_dataModel setValuesForKeysWithDictionary:dict];
        _detailView.dataModel = self.dataModel;
        
        // videoModel请求数据
        NSArray *videoArr = dic[@"videos"];
        for (NSDictionary *dict in videoArr)
        {
            _videoModel = [[AYSPlayVideoModel alloc] init];
            [_videoModel setValuesForKeysWithDictionary:dict];
            [self.videoArray addObject:_videoModel];
        }
        [_channelChooseCV reloadData];
        [_collectionView reloadData];
        
        [_postImageView sd_setImageWithURL:[NSURL URLWithString:self.dataModel.vthumburl]];
        self.titleLabel.text = self.dataModel.programname;
        _updateLabel.text = [NSString stringWithFormat:@"%@",_dataModel.episode];
        
        NSLog(@"array:%@",_videoModel.urlArray);
        if (_videoModel.urlArray.count != 0)
        {
            for (int i = 0; i <= _videoModel.urlArray.count / 100; i++)
            {
                _chooseButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
                _chooseButton.frame = CGRectMake(i*70 ,5, 60, 20);
                if (i == _videoModel.urlArray.count /100)
                {
                    [_chooseButton setTitle:[NSString stringWithFormat:@"%d-%ld",i * 100 + 1,_videoModel.urlArray.count] forState:(UIControlStateNormal)];
                }
                else
                {
                    [_chooseButton setTitle:[NSString stringWithFormat:@"%d-%d",i * 100 + 1,(i+1) * 100] forState:UIControlStateNormal];
                }
                _chooseButton.tag = 100 + i;
                [_chooseButton setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
                [_chooseButton setTitleColor:[UIColor redColor] forState:(UIControlStateHighlighted)];
                [_chooseScrollView addSubview:_chooseButton];
                [_chooseButton addTarget:self action:@selector(clickChooseButton:) forControlEvents:(UIControlEventTouchUpInside)];
            }
        }
        
        }
        error:^(NSError *error) {
        NSLog(@"播放详情数据请求失败");
    }];
}

// 点击收藏按钮
- (void)clickButton:(UIButton *)button
{
    [self p_favoriteMovie];
}

// 点击segmentControl改变页面
- (void)changeView:(UISegmentedControl *)segmentControl
{
    switch (segmentControl.selectedSegmentIndex)
    {
        case 0:
            [_mainScrollView addSubview:_chooseScrollView];
            [_mainScrollView addSubview:_collectionView];
            break;
            case 1:
            [_mainScrollView addSubview:_detailView];
            CGFloat height = [_detailView heightOfDetailView:_detailView.descLabel];
            _mainScrollView.contentSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT / 4 + 90 + height);
            break;
        default:
            break;
    }
}

//// 点击选择集数Button
//- (void)clickChooseButton:(UIButton *)button
//{
//    NSInteger index = 100-button.tag;
//    
//}

// collectionView方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (collectionView.tag == 101)
    {
        return _videoArray.count;
    }
    else
    {
        if (_videoModel.urlArray.count== 0)
        {
            return 1;
        }
        else
        {
            if (_videoModel.urlArray.count < 100)
            {
                return _videoModel.urlArray.count;
            }
            else
            {
                return 100;
            }
        }
        
    }
    
}

// 设置item大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView.tag == 102)
    {
        if (!_videoModel.urlModel.videodesc)
        {
            return CGSizeMake((SCREEN_WIDTH - 50) / 4 - 10, 20);
        }
        else
        {
            return CGSizeMake(SCREEN_WIDTH / 2 - 20, 40);
        }
    }
    else
    {
        return CGSizeMake(25, 25);
    }
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView.tag == 101)
    {
        AYSChannelChooseCell *cell1 = [collectionView dequeueReusableCellWithReuseIdentifier:@"channel" forIndexPath:indexPath];
        AYSPlayVideoModel *model = _videoArray[indexPath.row];
        NSArray *array = [model.videourl componentsSeparatedByString:@"/"];
        NSString *text = array[2];
        if ([text isEqualToString:@"www.letv.com"])
        {
            cell1.iconImageView.image = [UIImage imageNamed:@"leshi"];
        }
       else if ([text isEqualToString:@"tv.sohu.com"])
        {
            cell1.iconImageView.image = [UIImage imageNamed:@"souhu"];
        }
       else if ([text isEqualToString:@"www.iqiyi.com"])
        {
            cell1.iconImageView.image = [UIImage imageNamed:@"qiaiyi"];
        }
      else  if ([text isEqualToString:@"v.youku.com"])
        {
            cell1.iconImageView.image = [UIImage imageNamed:@"youku"];
        }
      else  if ([text isEqualToString:@"v.qq.com"])
        {
            cell1.iconImageView.image = [UIImage imageNamed:@"tengxun"];
        }
        else if([text isEqualToString:@"v.pps.tv"])
        {
            cell1.iconImageView.image = [UIImage imageNamed:@"pps"];
        }
        else if([text isEqualToString:@"v.pptv.com"])
        {
            cell1.iconImageView.image = [UIImage imageNamed:@"pptv"];
        }
        else if ([text isEqualToString:@"www.tudou.com"])
        {
            cell1.iconImageView.image = [UIImage imageNamed:@"tudou"];
        }
        else if ([text isEqualToString:@"www.fun.tv"])
        {
            cell1.iconImageView.image = [UIImage imageNamed:@"fengxing"];
        }
        else if ([text isEqualToString:@"www.wasu.cn"])
        {
            cell1.iconImageView.image = [UIImage imageNamed:@"huashu"];
        }
        else
        {
            cell1.iconImageView.image = [UIImage imageNamed:@"qita"];
        }
        
        return cell1;
    }
    else
    {
        AYSPlayVideoChooseCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"choose" forIndexPath:indexPath];
        
        if (_videoModel.urlArray.count == 0)
        {
            cell.numberLabel.text = @"1";
        }
        else
        {
            
            if (_videoModel.urlModel.videodesc.length == 0)
            {
            cell.numberLabel.text = [NSString stringWithFormat:@"%ld",indexPath.row +1];
            }
            else
            {
                AYSPlayUrlModel *model = _videoModel.urlArray[_videoModel.urlArray.count - indexPath.row - 1];
                cell.numberLabel.frame = CGRectMake(0, 0, SCREEN_WIDTH / 2 - 20, 20);
                cell.numberLabel.text = model.name;
                cell.descLabel.text = model.videodesc;
                [cell.contentView addSubview:cell.descLabel];
            }
            
        }
        
        return cell;
    }
    
}

// 点击collectionView
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [_dataBase executeUpdate:@"INSERT INTO WATCHRECORD (title) VALUES (?)", _dataModel.programname];
    if (collectionView.tag == 102)
    {
        if (_videoModel.urlArray.count == 0)
        {
            AYSVideoPlayerViewController *player = [[AYSVideoPlayerViewController alloc] init];
            player.url = ((AYSPlayVideoModel *)self.videoArray[0]).videourl;
            player.videoArray = self.videoArray;
            player.row = indexPath.row;
            [self.navigationController presentViewController:player animated:YES completion:nil];
        }
        else
        {
            AYSPlayVideoChooseCell *cell = (AYSPlayVideoChooseCell *)[collectionView cellForItemAtIndexPath:indexPath];
            cell.numberLabel.textColor = [UIColor redColor];
            AYSVideoPlayerViewController *player = [[AYSVideoPlayerViewController alloc] init];
            AYSPlayUrlModel *model = _videoModel.urlArray[_videoModel.urlArray.count - indexPath.row - 1];
            player.url =model.url;
            player.videoArray = self.videoModel.urlArray;
            player.row = indexPath.row;
            [self.navigationController presentViewController:player animated:YES
                                                  completion:nil];
        }
    }
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView.tag == 102)
    {
        AYSPlayVideoChooseCell *cell = (AYSPlayVideoChooseCell *)[collectionView cellForItemAtIndexPath:indexPath];
        cell.numberLabel.textColor = [UIColor whiteColor];
    }
   
}

// 收藏活动
- (void)p_favoriteMovie
{
    BOOL isFavorite = [[AYSDatabaseHandle shareInstance] isFavoriteMovieWithID:_dataModel.programID];
    if (YES == isFavorite)
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"该电影已经被收藏过" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
        
        return;
    }
    
    // 操作数据库，收藏活动
    _dataModel.isFavorite = YES;
    [[AYSDatabaseHandle shareInstance] insertNewMovie:_dataModel];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"收藏成功" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
    [alertView show];
    [self performSelector:@selector(p_removeAlertView:) withObject:alertView afterDelay:0.5];
    
}

- (void)p_removeAlertView:(UIAlertView *)alertView
{
    [alertView dismissWithClickedButtonIndex:0 animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
